/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved.
 */

package org.opengauss.service;

import org.opengauss.driver.DriverInfoManager;
import org.opengauss.driver.IDriverInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * description:this for FactoryInstance Class
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2021.
 *
 * @author Administrator
 * @version [openGauss_debug 0.0.1 2021/3/9]
 * @since 2021/3/9
 */
public class FactoryInstance {
    public static final String MYBATIS_CONF = "mybatis-config.xml";
    public static FactoryInstance INSTANCE = new FactoryInstance();
    private int[] sqlSessionLock = new int[0];
    private volatile SqlSessionFactory sqlSessionFactory = null;
    private volatile SqlSessionFactory druidSessionFactory = null;

    private FactoryInstance() {

    }

    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        return getSqlSessionFactory(DriverInfoManager.getInfo());
    }
    
//    public SqlSessionFactory getSqlSessionFactory(IDriverInfo info) throws IOException {
//        if (sqlSessionFactory != null) {
//            return sqlSessionFactory;
//        }
//        synchronized (sqlSessionLock) {
//            if (sqlSessionFactory != null) {
//                return sqlSessionFactory;
//            }
//            InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONF);
//            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, info.getProperties());
//            return sqlSessionFactory;
//        }
//    }
    
    public SqlSessionFactory getSqlSessionFactory(IDriverInfo info) throws IOException {
        return getSqlSessionFactory("development", info);
    }
    
    public SqlSessionFactory getSqlSessionFactory(String env, IDriverInfo info) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONF);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream, env, info.getProperties());
        return factory;
    }
    
    
    public SqlSessionFactory getDruidSessionFactory(String env) throws IOException {
        if (druidSessionFactory != null) {
            return druidSessionFactory;
        }
        synchronized (sqlSessionLock) {
            if (druidSessionFactory != null) {
                return druidSessionFactory;
            }
            InputStream inputStream = Resources.getResourceAsStream(MYBATIS_CONF);
            druidSessionFactory = new SqlSessionFactoryBuilder().build(inputStream, env);
            return druidSessionFactory;
        }
    }
}
